import ajax from '@/utils/ajax';
import {uncompile} from "../utils";

export const SET_USER_DATA = 'SET_USER_DATA';
let initUser = null;
if(window.__local.auth) {
  let auth = JSON.parse(uncompile(window.__local.auth))
  initUser = auth.user;
}
export default (state = initUser, action) => {
  switch(action.type) {
    case SET_USER_DATA:
      return action.payload;
    default:
      return state
  }
}

export const fetchUserData = () => async dispatch => {
  try {
    let resp = await ajax({
      method: 'get',
      url: 'http://localhost:8080/api/user'
    })
    dispatch({
      type: SET_USER_DATA,
      payload: resp
    })
  } catch (error) {
    console.error(error)
  }
}

/**
 * 设置用户信息
 * @params: userData
 * **/
export const setUserData = (params = {}) => (dispatch) => {
  try {
    dispatch({
      type: SET_USER_DATA,
      payload: params,
    });
  } catch(err) {
    console.error(error)
  }
};